﻿using System;
using System.Collections.Generic;

using TMS.ProjectServiceModel;
using MongoDB.Bson;
using M = MongoDB.Driver.Builders;

namespace TMS.ProjectServiceImplement.DAL
{
    /// <summary>
    /// <remarks>
    /// 
    /// </remarks>
    /// </summary>
    public class ProjectPublishDAL
    {
        public static List<Project> GetAllProject()
        {
            List<Project> list = new List<Project>();

            var collection = DataAccess.GetPublishDB<Project>("Project");
            var query = M.Query.LT("Status", new BsonInt32(6));
            var result = collection.Find(query);
            if (result != null)
            {
                foreach (var item in result)
                {
                    list.Add(item);
                }
            }

            return list;
        }

        public static Project Insert(Project project)
        {
            var collection = DataAccess.GetPublishDB<Project>("Project");
            var result = collection.Insert<Project>(project);
            if (result.Ok)
            {
                return project;
            }
            else
            {
                return null;
            }
        }

        public static Project Update(Project project)
        {
            var collection = DataAccess.GetPublishDB<Project>("Project");
            var query = M.Query.EQ("ID", new BsonInt32(project.ID));
            var search = collection.FindOne(query);
            if (search != null)
            {
                search.Description = project.Description;
                search.LastBuildDate = project.LastBuildDate;
                search.LastBuildMessage = project.LastBuildMessage;
                search.LastBuildStatus = project.LastBuildStatus;
                search.LastFromDate = project.LastFromDate;
                search.LastToDate = project.LastToDate;
                search.ProjectName = project.ProjectName;
                search.ProjectTitle = project.ProjectTitle;
                search.TestEnv = project.TestEnv;
                search.Status = project.Status;

                var result = collection.Save(search);
                if (result.Ok)
                {
                    return search;
                }
                else
                {
                    return null;
                }
            }

            return null;
        }

        public static void Delete(int id)
        {
            var collection = DataAccess.GetPublishDB<Project>("Project");
            collection.Remove(M.Query.EQ("ID", new BsonInt32(id)));
        }

        public static Project Get(int id)
        {
            var collection = DataAccess.GetPublishDB<Project>("Project");
            var query = M.Query.EQ("ID", new BsonInt32(id));
            return collection.FindOne(query);
        }
    }
}
